package com.heba.greenmulu.user;

import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.diary.DiaryListRecyclerAdapter;
import com.heba.adapter.diary.callback.DiaryItemListener;
import com.heba.bean.ItemShareObject;
import com.heba.bean.ShareObject;
import com.heba.bean.diary.ItemDiaryDetailObject;
import com.heba.config.CommonConfig;
import com.heba.dialog.CustomDialogView;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.ItemReportActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.popupwindow.DiaryCommentPopupWindow;
import com.heba.popupwindow.OpenMapPopupWindow;
import com.heba.popupwindow.SharePopupWindow;
import com.heba.popupwindow.callback.OpenMapClickListener;
import com.heba.popupwindow.callback.ShareListener;
import com.heba.utils.ToastShow;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户日记、朋友贴滚动列表
 * 点击日记显示的日记详情页
 * Created by jason on 2020/3/16.
 */
public class UserDiaryListActivity extends BaseActivity {

    private View view_background;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private DiaryListRecyclerAdapter recycleAdapter;

    /**
     * 分享彈出框
     */
    private SharePopupWindow sharePopupWindow;
    private ShareObject shareObject;

    private OpenMapPopupWindow openMapPopupWindow;
    private ItemDiaryDetailObject diaryDetailObject;
    private Location mlocation;
    /**
     * 評論彈出框
     */
    private DiaryCommentPopupWindow commentPopupWindow;

    /**
     * 接收的数据
     */
    private int intentType = 0;   //intentType为1表示显示日记详情，0表示显示日记列表
    private String intentDiaryID;  //显示详情页传递的id
    private String uID;  //需要获取数据的用户的ID
    private String nickName;  //显示的页面标题
    private int position;    //列表需要移动到的位置
    private List<ItemDiaryDetailObject> list;  //列表数据
    private String url;   //获取数据的url(区分我的日记列表和朋友贴列表)
    private String hashTagID;

    /**
     * 添加评论参数
     */
    private int currentPos;     //每個item的position
    private String diaryID;   //每個item的日記id
    private int type;     //判斷評論回復
    private String feedbackID;
    private String toUserID;

    private boolean isDiaryCollect;  //日記是否收藏

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview);
        EventBus.getDefault().register(this);
        initTopbar();
        findViewById();
        initView();
        initPopupWindow();
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
    }

    @Override
    protected void initView() {
        //获取数据
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            hashTagID = bundle.getString(CommonConfig.HASHTAG_ID, "");
            intentType = bundle.getInt(CommonConfig.TYPE, 0);
            intentDiaryID = bundle.getString(CommonConfig.DIARY_ID, "");
            uID = bundle.getString(CommonConfig.USER_ID);
            nickName = bundle.getString(CommonConfig.USER_NAME, "");
            position = bundle.getInt(CommonConfig.DIARY_POSITION, 0);
            list = (List<ItemDiaryDetailObject>) bundle.getSerializable(CommonConfig.DIARY_LIST);
            url = bundle.getString(CommonConfig.URL);
        }
        shareObject = new ShareObject();
        txt_title.setText(nickName);

        if (intentType == 1) {
            txt_title.setText(this.getResources().getString(R.string.diary_diary));
            if (list == null) {
                list = new ArrayList<>();
            }
        }

        if (!hashTagID.isEmpty()) {
            txt_title.setText(this.getResources().getString(R.string.diary_diary));
        }

        recycleAdapter = new DiaryListRecyclerAdapter(this, list);

        recycleAdapter.setDiaryItemListener(new DiaryItemListener() {
            @Override
            public void showSharePopup(View view, int position, ItemDiaryDetailObject object) {
                view_background.setVisibility(View.VISIBLE);
                currentPos = position;
                isDiaryCollect = object.getIsCollected() == 1;
                diaryID = object.getDiaryID();
                diaryDetailObject = object;
                if (mlocation != null){
                    mlocation = new Location(LocationManager.GPS_PROVIDER);
                }

                openMapPopupWindow.setmLocation(mlocation);
                openMapPopupWindow.setDiaryDetailObject(diaryDetailObject);

                shareObject.setShareTitle(String.format(UserDiaryListActivity.this.getResources().getString(R.string.share_diary_title), object.getAccount()));
                shareObject.setShareContent(object.getContent());
                if (object.getImageList() != null && !object.getImageList().isEmpty())
                    shareObject.setShareImageUrl(object.getImageList().get(0).getImageUrl());
                shareObject.setShareLink(object.getLink());
                sharePopupWindow.setShareObject(shareObject);

                switch (intentType) {
                    case 0:
                        if (Cfg.UserID.equals(uID) && url.equals("/User/PasteListing")) {
                            //標記頁面 顯示隱藏日記和移除標籤
                            sharePopupWindow.setShareList(updateShareList1(), updateShareList3());
                        } else {
                            if (Cfg.UserID.equals(object.getUserID())) {
                                sharePopupWindow.setShareList(updateShareList1(), updateShareList2(true));
                            } else {
                                sharePopupWindow.setShareList(updateShareList1(), updateShareList2(false));
                            }
                        }
                        break;
                    case 1:
                        if (Cfg.UserID.equals(object.getUserID())) {
                            sharePopupWindow.setShareList(updateShareList1(), updateShareList2(true));
                        } else {
                            sharePopupWindow.setShareList(updateShareList1(), updateShareList2(false));
                        }
                        break;
                    default:
                        break;
                }
                sharePopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
            }

            @Override
            public void showCommentPopup(View view, String diaryid, String userid) {
                diaryID = diaryid;
                type = 0;
                feedbackID = "";
                toUserID = userid;
                showCommentPopupView(view, type, feedbackID, toUserID, getResources().getString(R.string.diary_comment));
            }

            @Override
            public void showOpenMapPopup(View view, ItemDiaryDetailObject diaryDetailObject, Location mLocation) {
                showOpenMapPopupView(view,diaryDetailObject,mLocation);
            }
        });

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
        //设置动画执行时间为0  防止局部刷新时闪烁
        recyclerView.getItemAnimator().setChangeDuration(0);
        //滚动到指定位置
        recyclerView.scrollToPosition(position);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);
        //日记详情
        if (intentType == 1) {
            refreshLayout.setEnableLoadMore(false);
            refreshLayout.setEnableRefresh(false);
            /**
             * 获取日记详情API
             */
            getDiaryDetailData();
        }

        if (!hashTagID.isEmpty()) {
            refreshLayout.setEnableLoadMore(false);
            refreshLayout.setEnableRefresh(false);
        }

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refreshDiaryListData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getDiaryListData();
        });

    }

    /**
     * 分享彈出框
     */
    private void initPopupWindow() {
        openMapPopupWindow = new OpenMapPopupWindow(this,ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        openMapPopupWindow.setOpenMapClickListener(new OpenMapClickListener(this){
            @Override
            public void openGoogleMap(ItemDiaryDetailObject diaryDetailObject, Location mLocation) {
                super.openGoogleMap(diaryDetailObject, mLocation);
            }

            @Override
            public void onCancelClick() {
                super.onCancelClick();
            }

            @Override
            public void onOpenAppleMap() {
            }
        });

        sharePopupWindow = new SharePopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        sharePopupWindow.setShareList(updateShareList1(), updateShareList2(false));

        /**
         * 分享接口實現
         */
        sharePopupWindow.setOnShareListener(new ShareListener(this) {
            @Override
            public void collectDiary() {
                /**
                 * 收藏日記貼
                 */
                if (isDiaryCollect) {
                    ToastShow.displayToast(UserDiaryListActivity.this, getResources().getString(R.string.diary_has_been_collect));
                    return;
                }
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        ToastShow.displayToast(UserDiaryListActivity.this, getResources().getString(R.string.diary_collect_success));
                    }

                    @Override
                    public void Fail(String error) {

                    }
                }).collectDiary(UserDiaryListActivity.this, diaryID);
            }

            @Override
            public void reportDiary() {
                Bundle bundle = new Bundle();
                bundle.putInt(CommonConfig.TYPE, 2);
                bundle.putString(CommonConfig.REPORT_ID, diaryID);
                openActivity(ItemReportActivity.class, bundle);
            }

            @Override
            public void deleteDiary() {
                /**
                 * 删除日记
                 */
                new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                    @Override
                    public void onYesClick() {
                        progressDialog.show();
                        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                            @Override
                            public void Success() {
                                progressDialog.dismiss();
                                list.remove(currentPos);
                                recycleAdapter.notifyItemRemoved(currentPos);
                                ToastShow.displayToast(UserDiaryListActivity.this, getResources().getString(R.string.diary_delete_success));
                            }

                            @Override
                            public void Fail(String error) {
                                progressDialog.dismiss();
                            }
                        }).deleteDiary(UserDiaryListActivity.this, diaryID);
                    }

                    @Override
                    public void onNoClick() {

                    }
                }).showDialog(UserDiaryListActivity.this, getResources().getString(R.string.diary_delete_tips), "");
            }

            @Override
            public void hiddenDiary() {
                progressDialog.show();
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        progressDialog.dismiss();
                        list.remove(currentPos);
                        recycleAdapter.notifyItemRemoved(currentPos);
                        ToastShow.displayToast(UserDiaryListActivity.this, getResources().getString(R.string.diary_hidden_success));
                    }

                    @Override
                    public void Fail(String error) {
                        progressDialog.dismiss();
                    }
                }).hiddenDiary(UserDiaryListActivity.this, diaryID);
            }

            @Override
            public void removeTag() {
                progressDialog.show();
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        progressDialog.dismiss();
                        list.remove(currentPos);
                        recycleAdapter.notifyItemRemoved(currentPos);
                        ToastShow.displayToast(UserDiaryListActivity.this, getResources().getString(R.string.diary_remove_success));
                    }

                    @Override
                    public void Fail(String error) {
                        progressDialog.dismiss();
                    }
                }).removeTag(UserDiaryListActivity.this, diaryID);
            }
        });

        openMapPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });

        sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });

        /**
         * 評論彈出框
         */
        commentPopupWindow = new DiaryCommentPopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        commentPopupWindow.setOnDiaryCommentListener(content -> {
            /**
             * 用户留言处理
             */
            progressDialog.show();
            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                @Override
                public void Success() {
                    /**
                     * 留言评论成功，更新数据
                     */
                    progressDialog.dismiss();
                    commentPopupWindow.setCommentHint(getResources().getString(R.string.diary_comment));
                    commentPopupWindow.setCommentText("");
                    refreshDiaryListData();
                }

                @Override
                public void Fail(String error) {
                    progressDialog.dismiss();
                }
            }).addFeedback(UserDiaryListActivity.this, diaryID, type, content, toUserID, feedbackID);
        });
        commentPopupWindow.setOnDismissListener(() -> view_background.setVisibility(View.GONE));
    }

    /**
     * 分享至社交軟件
     */
    private List<ItemShareObject> updateShareList1() {
        List<ItemShareObject> shareList = new ArrayList<>();
        int[] ids = {R.drawable.icon_more_share_facebook, R.drawable.icon_more_share_whatsapp, R.drawable.icon_more_share_wechat, R.drawable.icon_more_share_friends};
        String[] contents = getResources().getStringArray(R.array.share_contents_normal);
        int[] shareTypes = {CommonConfig.SHARE_TO_FACEBOOK, CommonConfig.SHARE_TO_WHATSAPP, CommonConfig.SHARE_TO_WECHAT, CommonConfig.SHARE_TO_CIRCLE};
        for (int i = 0; i < ids.length; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids[i]);
            shareObject.setShareContent(contents[i]);
            shareObject.setShareType(shareTypes[i]);
            shareList.add(shareObject);
        }
        return shareList;
    }

    /**
     * 本地分享
     *
     * @param withDiaryDelete 是否包含删除日记
     * @return
     */
    private List<ItemShareObject> updateShareList2(boolean withDiaryDelete) {
        List<ItemShareObject> shareList = new ArrayList<>();
        int[] ids1 = {R.drawable.icon_more_collection, R.drawable.icon_more_report, R.drawable.icon_more_delete};
        String[] contents1 = getResources().getStringArray(R.array.share_contents_diary);
        int[] shareTypes1 = {CommonConfig.SHARE_TO_COLLECT_DIARY, CommonConfig.SHARE_TO_REPORT_DIARY, CommonConfig.SHARE_TO_DELETE_DIARY};
        int len = ids1.length;
        if (!withDiaryDelete) {
            len = ids1.length - 1;
        }
        for (int i = 0; i < len; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids1[i]);
            shareObject.setShareContent(contents1[i]);
            shareObject.setShareType(shareTypes1[i]);
            shareList.add(shareObject);
        }
        return shareList;
    }

    /**
     * 我的用户标记列表 添加隐藏日记和移除标签
     *
     * @return
     */
    private List<ItemShareObject> updateShareList3() {
        List<ItemShareObject> shareList = new ArrayList<>();
        int[] ids1 = {R.drawable.icon_more_collection, R.drawable.icon_more_report, R.drawable.icon_more_hidden, R.drawable.icon_more_delete};
        String[] contents1 = getResources().getStringArray(R.array.share_contents_diary1);
        int[] shareTypes1 = {CommonConfig.SHARE_TO_COLLECT_DIARY, CommonConfig.SHARE_TO_REPORT_DIARY, CommonConfig.SHARE_TO_HIDDEN_DIARY, CommonConfig.SHARE_TO_REMOVE_TAG};
        int len = ids1.length;
        for (int i = 0; i < len; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids1[i]);
            shareObject.setShareContent(contents1[i]);
            shareObject.setShareType(shareTypes1[i]);
            shareList.add(shareObject);
        }
        return shareList;
    }
    private  void showOpenMapPopupView(View view,ItemDiaryDetailObject diaryDetailObject,Location mlocation){
        openMapPopupWindow.setDiaryDetailObject(diaryDetailObject);
        openMapPopupWindow.setmLocation(mlocation);
        openMapPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }
    /**
     * 显示评论弹出框
     *
     * @param view
     * @param type      判断是日记留言 还是回复用户留言
     * @param commentID 回复用户留言ID
     * @param toUserID  回复目标用户ID
     * @param hint      输入框提示
     */
    private void showCommentPopupView(View view, int type, String commentID, String toUserID, String hint) {
        this.type = type;
        this.feedbackID = commentID;
        this.toUserID = toUserID;
        view_background.setVisibility(View.VISIBLE);
        commentPopupWindow.setCommentHint(hint);
        commentPopupWindow.showSoftKeyBoard();
        commentPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 获取日记列表数据
     */
    private void getDiaryListData() {
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", (list.isEmpty() || list.size() <= 18) ? 18 : list.size());
        params.put("UID", uID);
        client.get(Cfg.BaseUrl + url, params,
                new JSONHttpHelper.JSONHttpResponseHandler(UserDiaryListActivity.this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemDiaryDetailObject> diaryDetailObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemDiaryDetailObject>>() {
                                }.getType());
                                list.addAll(list.size(), diaryDetailObjects);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        closeRefreshView(refreshLayout);
                    }

                });
    }

    /**
     * 获取日记详情数据
     */
    private void getDiaryDetailData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("DiaryID", intentDiaryID);
        params.put("p", 1);
        params.put("pp", 3);
        client.get(Cfg.BaseUrl + "/Diary/DiaryDetail", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        ItemDiaryDetailObject detailObject = null;
                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            detailObject = new Gson().fromJson(jsonObject.toString(), ItemDiaryDetailObject.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 显示数据
                         */
                        if (null != detailObject) {
                            list.clear();
                            list.add(detailObject);
                            //刷新数据
                            recycleAdapter.notifyDataSetChanged();
                        }

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * 刷新列表數據
     */
    private void refreshDiaryListData() {
        Page = 1;
        isRefreshFromTop = true;
        if (intentType == 1) {
            getDiaryDetailData();
        } else {
            getDiaryListData();
        }
    }

    /**
     * 接收EventBus
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 更新列表數據
         */
        if (event.getEvent().equals(CommonConfig.EVENT_REFRESH_DIARY_LIST)) {
            refreshDiaryListData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //反註冊
        EventBus.getDefault().unregister(this);
    }
}
